import re

from django.contrib.auth.backends import ModelBackend

from users.models import User


def jwt_response_payload_handler(token,user = None,request = None):
    '''

    自定义jwt返回数据　因为认证只能返回token 的值　　满足不了我们的需求　
    '''

    return {

        'token':token,
        'user_id':user.id,
        'username':user.username
    }


'''
首先明确一下做什么事情
手机号　和　用户名　都可以登陆　
怎么去验证　　
之前使用的是django的认证的系统　　
所以要重写

'''


class UsernameModelBack(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):

        user = get_username(username)

        if user is not None and user.check_password(password):
            return user


def get_username(value):

    try:

        if re.match(r'1[3-9]\d{9}',value):

            user = User.objects.get(mobile=value)

        else:
            user = User.objects.get(username=value)
    except User.DoesNotExist:
        user = None

    return user